<?php

/**
 * component actions.
 *
 * @package    student_manager
 * @subpackage component
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class componentActions extends autocomponentActions
{

public function executeChangeQty(){
     $this->getResponse()->setTitle('WMS-Change-Qty-Component');
    if (!$this->getUser()->hasGroup('Administrator'))
    {
        return $this->forward('component', 'ViewWarehouse');
    }
    
    $id = $this->getRequestParameter('id');
    $type = $this->getRequestParameter('type');
    if ($this->getRequest()->isMethod('post')){

        $no = $this->getRequestParameter('no');
        if ($id && isset($no) && ($no != '') && isset($type) ){
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID, $id);
            $obj = WarehousePeer::doSelectOne($c);
            if ($obj){
                switch ($type)
                {
                    case 'needed':
                        $obj->setQtyneeded($no);
                        $obj->save();
                        $this->getUser()->setFlash('notice',  'change Qty needed successfully!');
                        return $this->forward('component','ViewWarehouse');
                    case 'closing':
                        $obj->setClosing($no);
	    		$obj->setOpening($no);
                        $obj->save();
	    		$this->getUser()->setFlash('notice',  'change Closing successfully!');
                        return $this->forward('component','ViewWarehouse');
                    case 'requested':
                        $obj->setQtyrequested($no);
                        $obj->save();
                        $this->getUser()->setFlash('notice',  'change Qty requested successfully!');
                        return $this->forward('component','ViewWarehouse');
                    case 'ordered':
                        $obj->setQtyordered($no);
                        $obj->save();
                        $this->getUser()->setFlash('notice',  'change Qty ordered successfully!');
                        return $this->forward('component','ViewWarehouse');
                }
            }
    	}
    }

    $c = new Criteria();
    $c->add(WarehousePeer::COMPONENT_ID, $id);
    $obj = WarehousePeer::doSelectOne($c);
    switch ($type)
    {
        case 'needed':
            $this->no = $obj->getQtyneeded();
            break;
        case 'closing':
            $this->no = $obj->getClosing();
            break;
        case 'requested':
            $this->no = $obj->getQtyrequested();
            break;
        case 'ordered':
            $this->no = $obj->getQtyordered();
            break;
    }
    $this->id = $id;
    $this->type = $type;
}

	public function executeFixWarehouse(){
             $this->getResponse()->setTitle('WMS-Fix-Warehouse');
		if ($this->getRequest()->isMethod('post'))
            {
            	if ($this->getRequestParameter('import_file')){
            		$inventory_file = trim($this->getRequestParameter('import_file')); 
            		$this->importfile = $inventory_file;           		
            	}            	
            	if ($this->getRequestParameter('productcode')){
            		$productcode = trim($this->getRequestParameter('productcode'));    
            		$this->productcode = $productcode;        		
            	}
	            if ($this->getRequestParameter('closing')){
            		$closing = trim($this->getRequestParameter('closing'));	  
            		$this->closing = $closing;          		
            	}
	            if ($this->getRequestParameter('startrow')){
            		$startrow = intval($this->getRequestParameter('startrow'));	     
            		$this->startrow = $startrow;       		
            	}
	            if ($this->getRequestParameter('endrow')){
            		$endrow = intval($this->getRequestParameter('endrow'));	 
            		$this->endrow = $endrow;           		
            	}
           		if ($this->getRequestParameter('sheetnumber')){
            		$sheetnumber = intval($this->getRequestParameter('sheetnumber'));	 
            		$this->sheetnumber = $sheetnumber;           		
            		$sheetnumber--;
            	}
            	
            	if (!isset($inventory_file) || !isset($productcode) || !isset($closing) || !isset($startrow) || !isset($endrow) || !isset($sheetnumber)){
            		$this->getUser()->setFlash('notice', 'Please enter all fields before submit');
            		return;
            	}
            	if (substr($inventory_file, strlen($inventory_file)- 3, 3) != 'xls'){
            		$this->getUser()->setFlash('notice', 'The file is not excel file!');
            		return;					
            	}
            	$data = new Spreadsheet_Excel_Reader();
				// Set output Encoding.
				$data->setOutputEncoding('utf-8');	
				$data->setUTFEncoder('mb');
				if (!file_exists($inventory_file)){
					$this->getUser()->setFlash('notice', 'The path excel file is not correct!');
            		return;					
				}
				$data->read($inventory_file);
				if (!$data) {
					$this->getUser()->setFlash('notice', 'Can not read data from excel file');
            		return;					
				}
            	$productcode = ord(strtoupper($productcode)) - ord("A") + 1;
            	$closing = ord(strtoupper($closing)) - ord("A") + 1;
            	
            	$bOK = false;
	
				for ($i = $startrow; $i <= $endrow; $i++){
					if(isset($data->sheets[$sheetnumber]['cells'][$i][$productcode]) 
					&& trim($data->sheets[$sheetnumber]['cells'][$i][$productcode])
					&&  isset($data->sheets[$sheetnumber]['cells'][$i][$closing]) 
					&& intval($data->sheets[$sheetnumber]['cells'][$i][$closing])){
						$fproductcode = trim($data->sheets[$sheetnumber]['cells'][$i][$productcode]);
						$fclosing = intval($data->sheets[$sheetnumber]['cells'][$i][$closing]);
						$c = new Criteria();
						$c->add(ComponentPeer::PRODUCTCODE, $fproductcode);
						$comp = ComponentPeer::doSelectOne($c);
						if ($comp){
							$c = new Criteria();
							$c->add(WarehousePeer::COMPONENT_ID, $comp->getId());
							$warehouse = WarehousePeer::doSelectOne($c);
							if ($warehouse){
								$warehouse->setClosing($fclosing);
								$warehouse->save();
								$bOK = true;
							}
						}						
					}
				}
				if ($bOK)
					$this->getUser()->setFlash('notice', 'Correct inventory successful!');
				else
					$this->getUser()->setFlash('notice', 'There is not any component to modify!');
            }

	}
	

public function executeView(){
     $this->getResponse()->setTitle('WMS-View-Component');
    $this->component = $this->getComponentOrCreate();       
    $this->labels = $this->getLabels();                 
}

public function executePrintMR(){
     $this->getResponse()->setTitle('WMS-Print-Component');
    $this->hasBOM = false;
    if ($this->getRequestParameter('mr_id')) {
        $mod = 'MR';
        $object = MRPeer::retrieveByPK($this->getRequestParameter('mr_id'));
        
        if (!$object) {
            $this->getRequest()->setError('print', 'This MR is not available.');        
            $this->forward('mr', 'list');
        }        
        $bom = BOMPeer::retrieveByPK($object->getBomId());
        $this->BOMcompGroupId = $bom->getComponentgroupId();
        $this->hasBOM = true;
    } 
    elseif  ($this->getRequestParameter('mr2_id')) {
        $mod = 'MRSUB';
        $object = MR2Peer::retrieveByPK($this->getRequestParameter('mr2_id'));
        
        if (!$object) {
            $this->getRequest()->setError('print', 'This MR is not available.');        
            $this->forward('mr2', 'list');
        }
    }    
    else {        
        $mod = 'MRRAW';
        $object = MR3Peer::retrieveByPK($this->getRequestParameter('mr3_id'));
        
        if (!$object) {
            $this->getRequest()->setError('print', 'This MR is not available.');        
            $this->forward('mr3', 'list');
        }
    }
    
    $compGroupId = $object->getComponentgroupId();
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
    $this->compsList = ComponentsPeer::doSelect($c);
    
    if ($object->getCategory() == CommonValues::$gMRCategory['key']['Project']) {
        $this->projectname = $object->getProject();
        $this->clientname = ProjectPeer::retrieveByPK($object->getProjectId())->getClient();
        $this->saleno = $object->getSaleno();
    }
        
    $this->mr = $object;
    
    
    $this->HOSName = '';
    $this->GDName = '';
    $this->ManagerName = '';

    $this->CreateName = '';

    //get create user name of object
    $user = sfGuardUserPeer::retrieveByPK($object->getUserId());
    $this->CreateName = $user->getFullname();
    
    $c = new Criteria();
    $c->add(ApprovalPeer::TYPE , CommonValues::$gApprovalType['key'][$mod]);
    $c->add(ApprovalPeer::OBJECT_ID , $object->getId());
    $approvalList = ApprovalPeer::doSelect($c);
    
    if ($approvalList && count($approvalList) > 0 ){
        foreach ($approvalList as $approval){
            $user = sfGuardUserPeer::retrieveByPK($approval->getUserId());
            if ($user) {
                if ($user->hasGroup('Support Head')) {
                    $this->HOSName = $user->getFullname();
                }
                elseif ($user->hasGroup('General Director')) {
                    $this->GDName = $user->getFullname();
                }
                elseif ($user->hasGroup('Production Manager') || $user->hasGroup('Project Head') || $user->hasGroup('L&W Manger')) {
                    $this->ManagerName = $user->getFullname();
                }
            }
        }
    }
    
}
  public function executeList()
  {
       $this->getResponse()->setTitle('WMS-Component-List');
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/component/filters');

    // pager
    $this->pager = new sfPropelPager('Component', 25);
    $c = new Criteria();
    $c->addDescendingOrderByColumn(ComponentPeer::ID );
    
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 'sf_admin/component')));
    $this->pager->init();
    // save page
    if ($this->getRequestParameter('page')) {
        $this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/component');
    }
  }

  
  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['productcode_is_empty']))
    {
      $criterion = $c->getNewCriterion(ComponentPeer::PRODUCTCODE, '');
      $criterion->addOr($c->getNewCriterion(ComponentPeer::PRODUCTCODE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['productcode']) && $this->filters['productcode'] !== '')
    {
      $c->add(ComponentPeer::PRODUCTCODE, '%'.strtr($this->filters['productcode'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['description_is_empty']))
    {
      $criterion = $c->getNewCriterion(ComponentPeer::DESCRIPTION, '');
      $criterion->addOr($c->getNewCriterion(ComponentPeer::DESCRIPTION, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['description']) && $this->filters['description'] !== '')
    {
      $c->add(ComponentPeer::DESCRIPTION, '%'.strtr($this->filters['description'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['category_is_empty']))
    {
      $criterion = $c->getNewCriterion(ComponentPeer::CATEGORY, '');
      $criterion->addOr($c->getNewCriterion(ComponentPeer::CATEGORY, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['category']) && $this->filters['category'] !== '')
    {
      $c->add(ComponentPeer::CATEGORY, $this->filters['category']);
    }
    
    if (isset($this->filters['componenttype_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(ComponentPeer::COMPONENTTYPE_ID, '');
      $criterion->addOr($c->getNewCriterion(ComponentPeer::COMPONENTTYPE_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['componenttype_id']) && $this->filters['componenttype_id'] !== '')
    {
      $c->add(ComponentPeer::COMPONENTTYPE_ID, $this->filters['componenttype_id']);
    }
    if (isset($this->filters['brand_is_empty']))
    {
      $criterion = $c->getNewCriterion(ComponentPeer::BRAND, '');
      $criterion->addOr($c->getNewCriterion(ComponentPeer::BRAND, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['brand']) && $this->filters['brand'] !== '')
    {
      $c->add(ComponentPeer::BRAND, '%'.strtr($this->filters['brand'], '*', '%').'%', Criteria::LIKE);
    }
  }

public function executeViewWarehouse(){
    CalcTime::Start();
     $this->getResponse()->setTitle('WMS-View-Warehouse');
    $this->filters = null;
    $this->pagenumber = 1;
    $this->maxperpage = 200;
    
    if ($this->getRequest()->hasParameter('filter'))
    {
        $this->filters = $this->getRequestParameter('filters');
        
        $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/component');
      $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/component/filters');
      $this->getUser()->getAttributeHolder()->add($this->filters, 'sf_admin/component/filters');
    }
    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/component/filters');
    
    if ($this->getRequest()->hasParameter('page'))
    {
        $this->pagenumber = $this->getRequestParameter('page');
    }
    
    $c = new Criteria();
    $c->addAscendingOrderByColumn(ComponentPeer::ID);
    
    if (isset($this->filters['productcode']) && $this->filters['productcode'] !== '')
    {
      $c->add(ComponentPeer::PRODUCTCODE, '%'.strtr($this->filters['productcode'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['description']) && $this->filters['description'] !== '')
    {
      $c->add(ComponentPeer::DESCRIPTION, '%'.strtr($this->filters['description'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['category']) && $this->filters['category'] !== '' && isset( CommonValues::$gCompCategory['key'][$this->filters['category']]))
    {
      $c->add(ComponentPeer::CATEGORY, CommonValues::$gCompCategory['key'][$this->filters['category']]);
    }
    if (isset($this->filters['brand']) && $this->filters['brand'] !== '')
    {
      $c->add(ComponentPeer::BRAND, '%'.strtr($this->filters['brand'], '*', '%').'%', Criteria::LIKE);
    }
    $this->componentList = ComponentPeer::doSelect($c);   
    
    $c->addJoin(WarehousePeer::COMPONENT_ID, ComponentPeer::ID, Criteria::LEFT_JOIN);
    $this->WHList = WarehousePeer::doSelect($c);
    
    $this->hasEditCompPermission = false;
    if ($this->getUser()->hasCredential('EDIT_COMP')){
        $this->hasEditCompPermission = true;
    }
}
    
    public function executeSLListBOMGroup()
    {
         $this->getResponse()->setTitle('WMS-Component-List-'.$this->getRequestParameter('code'));
        if ($this->getRequest()->hasParameter('code')){
            $this->code = $this->getRequestParameter('code');
        }
        
        $c = new Criteria();
        $this->forward404Unless($this->getRequestParameter('componentgroup_id'));

        $c = new Criteria();
        $c->add(MRPeer::BOM_ID, $this->getRequestParameter('bom_id'));
        $this->mr = MRPeer::doSelectOne($c);
        //if (!$this->mr) {echo '1'; exit();};

        $c= new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->getRequestParameter('componentgroup_id'));
        $c->addAscendingOrderByColumn(ComponentsPeer::COMPONENT_ID);
        $this->componentsList= ComponentsPeer::doSelect($c);
    }
    
    public function executeSLListModuleGroup()
    {   
        if ($this->getRequestParameter('code'))
        $this->getResponse()->setTitle('WMS-Component-List-'.$this->getRequestParameter('code'));
        else
        $this->getResponse()->setTitle('WMS-Component-List');    
        $this->backURL = $this->getRequestParameter('backURL');
        $this->backURL = str_replace('~1', '/', $this->backURL);
        $this->backURL = str_replace('~2', '?', $this->backURL);
        $this->backURL = str_replace('~3', '&', $this->backURL);
        $this->backURL = str_replace('~4', '=', $this->backURL);
        //echo $this->backURL; exit();
        $Authentication = $this->getRequestParameter('Authentication');
        if (!$Authentication || !$this->getUser()->hasCredential($Authentication))
            $this->redirect($this->backURL);
            
        $c = new Criteria();
        $this->forward404Unless($this->getRequestParameter('componentgroup_id'));
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->getRequestParameter('componentgroup_id'));
        $c->addAscendingOrderByColumn(ComponentsPeer::COMPONENT_ID);
        $this->componentsList= ComponentsPeer::doSelect($c);

        if ($this->getRequest()->hasParameter('NotShowDate')){
            $this->NotShowDate = 1;
        }
        if ($this->getRequest()->hasParameter('titleqty')){
            $this->TitleQty = $this->getRequestParameter('titleqty');
        }
        if ($this->getRequest()->hasParameter('titleqty2')){
            $this->TitleQty2 = $this->getRequestParameter('titleqty2');
        }
        if ($this->getRequest()->hasParameter('titleqty3')){
            $this->TitleQty3 = $this->getRequestParameter('titleqty3');
        }
        if ($this->getRequest()->hasParameter('titleqty4')){
            $this->TitleQty4 = $this->getRequestParameter('titleqty4');
        }

        if ($this->getRequest()->hasParameter('code')){
            $this->code = $this->getRequestParameter('code');
        }
        
    }
    
    public function executeSLListPOGroup()
    {
         $this->getResponse()->setTitle('WMS-Component-List-'.$this->getRequestParameter('code'));
        $this->backURL = $this->getRequestParameter('backURL');

        if ($this->getRequest()->hasParameter('code')){
            $this->code = $this->getRequestParameter('code');
        }
        
        
        $this->backURL = $this->getRequestParameter('backURL');
        $this->backURL = str_replace('~1', '/', $this->backURL);
        $this->backURL = str_replace('~2', '?', $this->backURL);
        $this->backURL = str_replace('~3', '&', $this->backURL);
        $this->backURL = str_replace('~4', '=', $this->backURL);

         //echo $this->backURL; exit();
        $Authentication = $this->getRequestParameter('Authentication');
        if (!$Authentication || !$this->getUser()->hasCredential($Authentication))
            $this->redirect($this->backURL);
        
        $c = new Criteria();
        $this->forward404Unless($this->getRequestParameter('componentgroup_id'));
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->getRequestParameter('componentgroup_id'));
        $c->addAscendingOrderByColumn(ComponentsPeer::COMPONENT_ID);
        $this->componentsList= ComponentsPeer::doSelect($c);
    }
    
    public function executeListAjax()
    {
         $this->getResponse()->setTitle('WMS-Component-List');
        $c = new Criteria();
        if ($this->getRequestParameter('description'))	    {
            $c->add(ComponentPeer::DESCRIPTION, '%'.$this->getRequestParameter('description').'%', Criteria::LIKE );
        }
        if ($this->getRequestParameter('productcode'))        {
            $c->add(ComponentPeer::PRODUCTCODE, '%'.$this->getRequestParameter('productcode').'%', Criteria::LIKE);
        }
        if ($this->getRequestParameter('category')>=0)        {        
            $c->add(ComponentPeer::CATEGORY, $this->getRequestParameter('category'));
        }
        $this->componentList= ComponentPeer::doSelect($c);
    }

    public function executeListPsAjax()
    {
        $c = new Criteria();
        if ($this->getRequestParameter('description'))	    {
            $c->add(ComponentPeer::DESCRIPTION, '%'.$this->getRequestParameter('description').'%', Criteria::LIKE );
        }
        if ($this->getRequestParameter('productcode'))        {
            $c->add(ComponentPeer::PRODUCTCODE, '%'.$this->getRequestParameter('productcode').'%', Criteria::LIKE);
        }
        if ($this->getRequestParameter('category')>=0)        {
            $c->add(ComponentPeer::CATEGORY, $this->getRequestParameter('category'));
        }
        $this->componentList= ComponentPeer::doSelect($c);
    }
    
    public function executeListComponentsAjax()
    {
        $c = new Criteria();
        if ($this->getRequestParameter('componentgroup_id'))	    {
            $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->getRequestParameter('componentgroup_id'));
        }        
        $this->componentsList= ComponentsPeer::doSelect($c);
    }
    public function executeListCompByBOMAjax()
    {
        $c = new Criteria();
        if ($this->getRequestParameter('bom_id'))	    {
            $bom = BOMPeer::retrieveByPK($this->getRequestParameter('bom_id'));
            if ($bom){
                $c->add(ComponentsPeer::COMPONENTGROUP_ID, $bom->getComponentgroupId());
                $this->componentsList= ComponentsPeer::doSelect($c);
            }
        }        
    }

public function executeDelete()
  {
     $this->getResponse()->setTitle('WMS-Del-Component');
    $this->component = ComponentPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->component);

    if (!$this->getUser()->hasGroup('Administrator'))
    {
        $this->getRequest()->setError('delete', 'You don\'t have admin permission to delete this component.');
        return $this->forward('component', 'list');
    }

    try
    {
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID, $this->component->getId());
        $wh = WarehousePeer::doSelectOne($c);
        if ($wh)
            $wh->delete();
      $this->deleteComponent($this->component);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Component. Make sure it does not have any associated items.');
      return $this->forward('component', 'list');
    }

    return $this->redirect('component/list');
  }
public function executeEdit()
  {
    $this->getResponse()->setTitle('WMS-Edit-Component');
    $this->component = $this->getComponentOrCreate();

    if ($this->getRequest()->isMethod('post'))
    {
      $this->updateComponentFromRequest();

      
      $c = new Criteria();      
      $c->add(ComponentPeer::PRODUCTCODE, $this->component->getProductcode());
      $comp = ComponentPeer::doSelect($c);
      if (
              ($this->component->getId() && count($comp)> 1)
          || ($this->component->getId() && count($comp)==1 && $comp[0]->getId() != $this->component->getId())
          || (!$this->component->getId() && count($comp)>0)
                  ){
          $this->labels = $this->getLabels();
          $this->getRequest()->setError('edit', 'Could not save the edited Components. Product code is duplicated');
          return ;
      }

      $c = new Criteria();
      $c->add(ComponentPeer::DESCRIPTION, $this->component->getDescription(), Criteria::LIKE);
      $comp = ComponentPeer::doSelect($c);
      if (
              ($this->component->getId() && count($comp)> 1)
          || ($this->component->getId() && count($comp)==1 && $comp[0]->getId() != $this->component->getId())
          || (!$this->component->getId() && count($comp)>0)
                  ){

          $this->labels = $this->getLabels();

          $this->getRequest()->setError('edit', 'Could not save the edited Components. Description is duplicated');
          return ;
      }

      
      if ($this->component->getCategory() != CommonValues::$gCompCategory['key']['Sub Component']){
        $this->component->setMinstockqty(null);
      }

      try
      {
        $this->saveComponent($this->component);
        
        //kiem tra tham chieu
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID, $this->component->getId());
        $find = WarehousePeer::doSelect($c);
        if (!$find){
            
            //them tham chieu component id vao warehouse
            $warehouse  = new Warehouse();
            $warehouse->setComponentId($this->component->getId());
            $warehouse->save();      
            
            //them tham chieu warehouse id vao component
            $this->component->setWarehouseId($warehouse->getId());
            $this->component->save();
        }
      }
      catch (PropelException $e)
      {
        $this->getRequest()->setError('edit', 'Could not save the edited Components.');
        return $this->forward('component', 'list');
      }

      $this->getUser()->setFlash('notice', 'Your modifications have been saved');

      if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('component/create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('component/list');
      }
      else
      {
        return $this->redirect('component/edit?id='.$this->component->getId());
      }
    }
    else
    {
      $this->labels = $this->getLabels();
    }
  }


public function executeImportExcelToInventory()
  {
        
    $data = new Spreadsheet_Excel_Reader();
	// Set output Encoding.
	$data->setOutputEncoding('utf-8');	
	$data->setUTFEncoder('mb');
	$data->read('D:\PROJECT\SUNLIGHT\MIGRATION\Inventory1109.xls');
	
	for ($i = 5; $i <= $data->sheets[2]['numRows']; $i++){
		if(isset($data->sheets[2]['cells'][$i][4]) && trim($data->sheets[2]['cells'][$i][4]) && !isset($data->sheets[2]['cells'][$i][5])){
			$typegroup = trim($data->sheets[2]['cells'][$i][4]);
			$pos = strpos($typegroup, '/');
			if (!$pos) $pos = -1;
			$typegroup = substr($typegroup, $pos + 1);
			$typegroup = trim($typegroup);
		}
		
		$comp = new Component();	
		if(isset($data->sheets[2]['cells'][$i][3]) && trim($data->sheets[2]['cells'][$i][3])){			
			$productcode =trim($data->sheets[2]['cells'][$i][3]);
			$c= new Criteria();
			$c->add(ComponentPeer::PRODUCTCODE, $productcode);
			$res = ComponentPeer::doSelectOne($c);
			if ($res){
				echo "duplicated row: $i\n";
				continue;
			}
			$comp->setProductcode(trim($data->sheets[2]['cells'][$i][3]));
		} 
		else 
			continue;
			
		
		if(isset($data->sheets[2]['cells'][$i][14]) && trim($data->sheets[2]['cells'][$i][14])){
			$cate = trim($data->sheets[2]['cells'][$i][14]); 			
			$comp->setCategory($cate);
		}
		
		if(isset($data->sheets[2]['cells'][$i][4]) && trim($data->sheets[2]['cells'][$i][4])){
			$description = trim($data->sheets[2]['cells'][$i][4]); 			
			$comp->setDescription($description);
			
			$pos = strpos($description, ' ');
			$type = substr($description, 0, $pos);
			if ($type){
				$c= new Criteria();
				$c->add(ComponentTypePeer::NAME, $type);
				$res = ComponentTypePeer::doSelectOne($c);
				if ($res){
					$comp->setComponenttypeId($res->getId());
				} else {
					$compType = new ComponentType();
					$compType->setName($typegroup);
					$compType->save();
					$comp->setComponenttypeId($compType->getId());
				}
			}
		}
		
		if(isset($data->sheets[2]['cells'][$i][5]) && trim($data->sheets[2]['cells'][$i][5])){			
			$unit = trim($data->sheets[2]['cells'][$i][5]);
			$c = new Criteria();
			$c->add(ComponentUnitPeer::NAME, $unit);
			$res = ComponentUnitPeer::doSelectOne($c);
			if ($res){
				$comp->setComponentunitId($res->getId());
			} else {
				$compUnit = new ComponentUnit();
				$compUnit->setName($unit);
				$compUnit->save();
				$comp->setComponentunitId($compUnit->getId());
			}
		}
		
		if(isset($data->sheets[2]['cells'][$i][6]) && trim($data->sheets[2]['cells'][$i][6])){			
			$comp->setBrand(trim($data->sheets[2]['cells'][$i][6]));
		}
		
		if(isset($data->sheets[2]['cells'][$i][13]) && trim($data->sheets[2]['cells'][$i][13])){			
			$comp->setLocation(trim($data->sheets[2]['cells'][$i][13]));
		}
		
		if(isset($data->sheets[2]['cells'][$i][11]) && trim($data->sheets[2]['cells'][$i][11])){			
			$comp->setMinstockqty(trim($data->sheets[2]['cells'][$i][11]));
			$comp->setCategory(1);
		}
		$comp->save();
		$warehouse = new Warehouse();
		$warehouse->setComponentId($comp->getId());
			
		if(isset($data->sheets[2]['cells'][$i][7]) && trim($data->sheets[2]['cells'][$i][7])){
			$warehouse->setOpening(trim($data->sheets[2]['cells'][$i][7]));
		}
		
		if(isset($data->sheets[2]['cells'][$i][8]) && trim($data->sheets[2]['cells'][$i][8])){
			$warehouse->setTotalin(trim($data->sheets[2]['cells'][$i][8]));
		}
		
		if(isset($data->sheets[2]['cells'][$i][9]) && trim($data->sheets[2]['cells'][$i][9])){
			$warehouse->setTotalout(trim($data->sheets[2]['cells'][$i][9]));
		}
		
	
		if(isset($data->sheets[2]['cells'][$i][10]) && trim($data->sheets[2]['cells'][$i][10])){
			$warehouse->setClosing(trim($data->sheets[2]['cells'][$i][10]));
		}
		$warehouse->save();
		
		echo "import row $i\n";
	}
	echo 'Successful!'; exit();
  }
  
  
  public function executeImportExcelToType()
  {
        
    $data = new Spreadsheet_Excel_Reader();
	// Set output Encoding.
	$data->setOutputEncoding('utf-8');	
	$data->setUTFEncoder('mb');
	$data->read('D:\PROJECT\SUNLIGHT\MIGRATION\Inventory1109.xls');
	
	
	for ($i = 1; $i <= $data->sheets[7]['numRows']; $i++){
		if(isset($data->sheets[7]['cells'][$i][1]) && trim($data->sheets[7]['cells'][$i][1])){			
			$type =trim($data->sheets[7]['cells'][$i][1]);
			$objtype = new ComponentType();
			$objtype->setName($type);
			$objtype->save();
		}	
	}
	echo 'Successful!'; exit();
  }
  

}
  
